package com.penghaisoft.microwms.product.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.MdContract;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.MSBarCode;
import com.penghaisoft.microwms.common.wms.model.ProBarcode;
import com.penghaisoft.microwms.common.wms.model.ProCheckIn;
import com.penghaisoft.microwms.product.dao.MSBarCodeMapper;
import com.penghaisoft.microwms.product.dao.MdContractMapper;
import com.penghaisoft.microwms.product.dao.ProBarcodeMapper;
import com.penghaisoft.microwms.product.dao.ProCheckInMapper;
import com.penghaisoft.microwms.product.service.IProCheckInService;

/**
 * @ClassName: ProCheckInServiceImpl
 * @Description: 成品积压库存登记表
 * @author luoteng
 * @date 2018年11月5日 上午10:45:18
 */
@Service("proCheckInService")
public class ProCheckInServiceImpl extends BaseService implements
		IProCheckInService {
	@Resource
	private ProCheckInMapper proCheckInMapper;

	@Resource
	private ProBarcodeMapper proBarcodeMapper;

	@Resource
	private MSBarCodeMapper mSBarCodeMapper;
	
	@Resource
	private MdContractMapper mdContractMapper;

	/**
	 * 新增记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp create(ProCheckIn proCheckIn) {
		proCheckInMapper.create(proCheckIn);
		return success();
	}

	/**
	 * 删除记录（逻辑删除）
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp delete(ProCheckIn proCheckIn) {
		proCheckInMapper.delete(proCheckIn);
		return success();
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @param baseResource
	 * @return
	 */
	@Override
	public Pager<ProCheckIn> findListByCondition(int page, int rows,
			ProCheckIn condition) {
		Pager<ProCheckIn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = proCheckInMapper.queryCount(condition);
		List<ProCheckIn> records = new ArrayList<ProCheckIn>();
		if (size > 0) {
			records = proCheckInMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * 查询单条
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public ProCheckIn findById(String id) {
		return proCheckInMapper.queryById(id);
	}

	/**
	 * 修改记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp update(ProCheckIn proCheckIn) {
		proCheckInMapper.updateBySelect(proCheckIn);
		return success();
	}

	@Override
	public List<ProCheckIn> queryByAny(ProCheckIn proCheckIn) {
		return proCheckInMapper.queryByAny(proCheckIn);
	}

	@Override
	@Transactional
	public Resp batchInsert(List<ProCheckIn> list, String checkInNo,
			String loginName) {
		Date now = new Date();
		HashSet<String> allSet = new HashSet<String>();
		for (int i = 0; i < list.size(); i++) {
			ProCheckIn tmpInsertOb = list.get(i);

			StringBuffer uniqueStr = new StringBuffer("");
			uniqueStr.append(tmpInsertOb.getModel());
			uniqueStr.append(tmpInsertOb.getModelType());
			if (allSet.contains(uniqueStr.toString())) {
				Resp resp = new Resp();
				resp.setCode(Constant.FAIL);
				resp.setMsg("选择的型号、型号类型重复");
				return resp;
			} else {
				allSet.add(uniqueStr.toString());
			}
		}

		for (int i = 0; i < list.size(); i++) {
			ProCheckIn tmpInsertOb = list.get(i);

			// 合同编号、型号、型号类型、需求数量 页面传递的参数已经提供
			tmpInsertOb.setCheckInNo(checkInNo);
			tmpInsertOb.setActiveFlag("1");
			tmpInsertOb.setGmtCreate(now);
			tmpInsertOb.setCreateBy(loginName);
			// 入库数量（个数）
			tmpInsertOb.setInAmount(0);
			// 是否生成条码： 1：是 0：否
			tmpInsertOb.setUserDefined2("0");

			proCheckInMapper.create(tmpInsertOb);
		}

		return success();
	}

	/*
	 * @Title: createBarcode
	 * 
	 * @Description: 根据登记单号生成条码
	 * 
	 * @author luoteng
	 * 
	 * @date 2018年11月5日 下午12:01:08
	 */
	@Override
	@Transactional
	public Resp createBarcode(List<ProCheckIn> list,
			HashMap<String, List<String>> barcodeMap, String loginName) {
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		Date now = new Date();
		
		
		MdContract mdContract = new MdContract();
		mdContract.setContractNo(list.get(0).getContractNo());
		mdContract.setActiveFlag("1");
		
		List<MdContract> contractList = mdContractMapper.queryByAny(mdContract);
		String customerName = null;
		if(contractList != null){
			customerName = contractList.get(0).getUserDefined1();
		}
		
		for (ProCheckIn tmp : list) {
			// 是否生成条码： 1：是 0：否
			tmp.setUserDefined2("1");
			Integer rtnNum = proCheckInMapper.updateBySelectNew(tmp);
			if(rtnNum != null && rtnNum < 1) {
				throw new RuntimeException("当前登记单号正在处理，请勿重复提交！");
			}
			
			Integer amount = tmp.getAmount();
			List<String> barCodeList = barcodeMap.get(tmp.getModel());
			for (int i = 0; i < amount; i++) {
				ProBarcode proBarcode = new ProBarcode();
				proBarcode.setUserDefined2(tmp.getCheckInNo());
				proBarcode.setUserDefined3(tmp.getCheckInId().toString());
				proBarcode.setContractNo(tmp.getContractNo());
				// TODO添加默认长度
				// rawBarcode.setAmount(amount);
				proBarcode.setUnit(tmp.getUserDefined1());
				proBarcode.setModel(tmp.getModel());
				proBarcode.setModelDesc(tmp.getModelDesc());
				proBarcode.setModelType(tmp.getModelType());

				proBarcode.setBarcode(barCodeList.get(i));
				// 状态 0：未打印 1：已打印
				proBarcode.setStatus("0");
				// 入库状态：0 未入库 1已入库
				proBarcode.setUserDefined1("0");
				proBarcode.setCreateBy(loginName);
				proBarcode.setGmtCreate(now);
				proBarcode.setActiveFlag("1");
				// 供应商名称
				// proBarcode.setUserDefined5(tmp.getUserDefined4());
				// 是否合格：0-不合格 1-合格
				// proBarcode.setUserDefined6("1");

				proBarcodeMapper.create(proBarcode);

				MSBarCode record = new MSBarCode();
				record.setBarCode(barCodeList.get(i));
				record.setModelCode(tmp.getModel());
				record.setModelType(tmp.getModelType());
				record.setContractNo(tmp.getContractNo());
				// record.setSpecification(condition.getAmount().toString());
				record.setUpdateDate(now);
				record.setBatchCode(tmp.getCheckInNo());
				
				record.setShortCode(splitByHyphen(tmp.getModel()));
				record.setCustomer(customerName);
				// 产品类型：0：原材料 1：成品
				record.setProductType("1");
				// 条码打印接口表
				mSBarCodeMapper.insertSelective(record);
			}
		}

		return resp;
	}

	private String splitByHyphen(String modelCode) {
		String result = "";
		int tindex = modelCode.indexOf("-");

		if (tindex == -1) {
			result = splitByStar(modelCode);
		} else {
			String[] parts = modelCode.split("-");
			result += splitByStar(parts[0]);
			result += "-";
			result += splitByStar(parts[1]);
		}
		return result;
	}

	private String splitByStar(String modelCode) {
		int tindex = modelCode.indexOf("*");
		if (tindex == -1) {
			return modelCode;
		}
		return modelCode.split("\\*")[0];
	}
}
